<?php
declare(strict_types=1);
namespace Helper;
class Ollama
{
    protected static string $host ='http://172.30.32.1:11434';
    public static function chat($message,$call,$model='qwen2:1.5b')
    {
        $msg = ["model"=> $model,'messages'=>[
            ['role'=>'user','content'=>$message]
        ]];

        $callback = function ($ch, $data) use($call){
            $call($data);
            return strlen($data);
        };
        self::send('chat',$msg,$callback);
    }

    private static function send($api,$data,$callback)
    {

        $header = array(
            'Accept: application/json',
            'Content-Type: application/json',
            //'Authorization: Bearer ' . $apiKey
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, self::$host. '/api/'.$api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
        curl_exec($ch);
        curl_close($ch);
        //var_dump($data);
        //return $data;
    }
}

